class AccountController < ApplicationController
  before_filter :authorize, :except => [:login,:register]
  layout "admin"
    def register
	  @sflag = " "

      @user = User.new(params[:user])
      if request.post? and @user.save
        flash.now[:notice] = "You have successfully registered!"

        @user = User.new
        @sflag = "register"
        

      
      end

  end
  def login
    
    if using_open_id?
      open_id_authentication
    elsif params[:email_addr]
    		      user = User.authenticate(params[:email_addr], params[:password])
		      if user
		        session[:user_id] = user.id   
		        redirect_to(:controller => "index")
		      else
		        flash[:notice] = "Invalid user/password combination,Note that you need to register first if have not registered yet!"
		      end
		    
     # password_authentication(params[:email_addr], params[:password])
    end
  end
  def logout



    session[:user_id] = nil
    flash[:notice] = "Logged out"
      @loflag = "logout"
#      render :action => 'login'
    redirect_to( :controller => "account",:action => "login")
  end
  protected
  
    def password_authentication(email_addr1, password1)
      if @current_user = User.authenticate(params[:email_addr], params[:password])
        successful_login
      else
        failed_login("Invalid login or password")
      end
    end
  
    def open_id_authentication
      authenticate_with_open_id do |result, identity_url|
        if result.successful?
          if @current_user = User.find_or_create_by_identity_url(identity_url)
            successful_login
          else
            failed_login "Sorry, no user by that identity URL exists (#{identity_url})"
          end
        else
          failed_login result.message
        end
      end
    end

  private
  
    def successful_login
            session[:user_id] = @current_user.id 
      redirect_to(:controller => "index")
      #redirect_back_or_default(index_url)
      flash[:notice] = "Logged in successfully"
    end

    def failed_login(message)
      redirect_to(:action => 'login')
      flash[:warning] = message
    end

end
